<?php
namespace frontend\modules\yii\widgets;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

/**
 * A menu imitate the sidebar of https://docs.docker.com/get-started/
 *
 * @note It's depend on bootstrap;
 *
 * @example :
 * ```php
 * echo \frontend\modules\yii\widgets\Menu::widget([
 *      'items' => [
 *          [
 *              'label' => 'Overview',
 *              'url' => ['/yii/bootstrap/index'],
 *              'items' => [
 *                  [
 *                      'label' => 'Reports',
 *                      'items' => [
 *                          ['label' => 'Reports', 'url' => ['javascript:void(0)']],
 *                          ['label' => 'Reports', 'url' => ['javascript:void(0)']],
 *                      ]
 *                  ],
 *                  ['label' => 'Reports', 'url' => ['javascript:void(0)']],
 *                  ['label' => 'Reports', 'url' => ['javascript:void(0)']],
 *                  ['label' => 'Reports', 'url' => ['javascript:void(0)']],
 *               ]
 *           ],
 *           ['label' => 'Reports', 'url' => ['/yii/bootstrap/index']],
 *           ['label' => 'Analytics', 'url' => ['/yii/bootstrap/index']],
 *           ['label' => 'Export', 'url' => ['/yii/bootstrap/index']],
 *           ['label' => 'Analytics', 'url' => ['/yii/bootstrap/index1']],
 *       ],
 *   ]);
 * ```
 * @author chenzhiwei <chenzhiweiwk@qq.com>
 * @date   2021/08/31
 */
class Menu extends \yii\widgets\Menu
{
    public $ulTemplate = '<a role="button" data-toggle="collapse" href="#{id}" aria-expanded="true" aria-controls="{id}">{label} <span class="collapse-arrow" aria-hidden="true"></span></a>';
    public $id = 0;
    public $idUnique = "id_";
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->options = array_merge($this->options, ['class' => 'nav nav-sidebar']);
        $this->submenuTemplate = "\n<ul class='collapse nav nav-sidebar submenu' id='{id}'>\n{items}\n</ul>\n";
        $this->linkTemplate =  '<a href="#" data-href="{url}">{label}</a>';
        $this->idUnique .= uniqid();
        $this->addCss();
        $this->addJs();
    }

    public function addCss(){
        $css = <<<CSS
.submenu li {
    margin-left: 10px;
}
.collapse-arrow {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 2px;
    vertical-align: middle;
    border-top: 4px dashed;
    border-top: 4px solid \9;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
    float: right;
    margin-top: 8px;
}

.nav > li > a:focus {
    text-decoration: none;
    background-color: #eee;
}
.nav > li > a.activeMenu {
    background: #f5f8fa;
    border-left: 4px solid #2697ed;
    font-weight: 600;
}
CSS;

        $this->view->registerCss($css, [], "menu-css-key");
    }

    public function addJs(){
        $js = <<<JS
$(".submenu a").click(function(){
    $(".submenu a").removeClass('activeMenu');
    $(this).addClass('activeMenu');
    var that = this;
    if(that.dataset.href){
        $.ajax({
        type: 'GET',
        url: that.dataset.href,
        dataType: 'text',
        success: function(res){
            $('.content-body').empty().append(res);
            var home = '<li>' + $('.breadcrumb li:first').html() + '</li>';
            var breadcrumbs = "";
            $.each($(that).parents('li'), function(k,v){
                breadcrumbs = '<li>' + v.firstChild.innerText + '</li>' +  breadcrumbs;
            });
            $('.breadcrumb').empty().append(home + breadcrumbs);
 
            //生成右边导航栏
            createCatalogue();
        },
        error: function(url, options){
            console.info(url,options);
        }
    });
    }
    
});
JS;
        $this->view->registerJs($js, View::POS_READY, "menu-js-key");
        $js = <<<JS
function menuClick(url){
   // $.ajax({
   //      type: "GET",
   //      data: {},
   //      return
   //     
   //  });
}
JS;
        $this->view->registerJs($js, View::POS_HEAD, "menu-js-key");
    }

    protected function renderItem($item)
    {
        if (isset($item['url']) && !isset($item["items"])) {
            $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate);
            if (isset($item["items"])) {
                $template = $this->ulTemplate;
            }
//            if (strpos($item["url"][0], 'javascript') !== false){
//                $url = $item['url'][0];
//            } else {
//                $url = Html::encode(Url::to($item['url']));
//            }
            return strtr($template, [
                '{url}' => Html::encode(Url::to($item['url'])),
                '{label}' => $item['label'],
            ]);
        }

        $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
        if (isset($item["items"])) {
            $template = $this->ulTemplate;
        }


        return strtr($template, [
            '{label}' => $item['label'],
            '{id}' => $this->idUnique . $this->id
        ]);
    }


    protected function renderItems($items)
    {
        $n = count($items);
        $lines = [];
        $this->id++;
        foreach ($items as $i => $item) {
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
            $tag = ArrayHelper::remove($options, 'tag', 'li');
            $class = [];
            if ($item['active']) {
                $class[] = $this->activeCssClass;
            }
            if ($i === 0 && $this->firstItemCssClass !== null) {
                $class[] = $this->firstItemCssClass;
            }
            if ($i === $n - 1 && $this->lastItemCssClass !== null) {
                $class[] = $this->lastItemCssClass;
            }
            Html::addCssClass($options, $class);

            $menu = $this->renderItem($item);
            if (!empty($item['items'])) {
                $submenuTemplate = ArrayHelper::getValue($item, 'submenuTemplate', $this->submenuTemplate);
                $menu .= strtr($submenuTemplate, [
                    '{id}' => $this->idUnique . $this->id,
                    '{items}' => $this->renderItems($item['items']),
                ]);
            }
            $lines[] = Html::tag($tag, $menu, $options);
        }

        return implode("\n", $lines);
    }
}
